//
//  CodeInputController.m
//  BrotherMovProject
//
//  Created by zhibao on 2022/1/17.
//

#import "LoginCodeInputController.h"
#import "SMSCodeInputView.h"
@interface LoginCodeInputController (){
    UIButton *_nextBtn;
}
@property (strong, nonatomic) SMSCodeInputView *inputView;
@property (nonatomic,  strong)   NSTimer *mtTimer;
@property (nonatomic , assign)   NSInteger num;  //倒数计数
@end

@implementation LoginCodeInputController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = @"";
    self.view.backgroundColor = UIColor.whiteColor;
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, NAVIH + 40, 300, 30)];
    label.text = LocalizedString(@"输入验证码");
    label.font = MY_SCALE_BoldFont(26);
    label.textColor = MYBlock;
    [self.view addSubview:label];
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(20, label.bottom + 20, 300, 26)];
    label1.text = [NSString stringWithFormat:@"%@+%@ %@",LocalizedString(@"已发送至 "),self.areaCode,self.phone];
    label1.font = MY_SCALE_RegularFONT(13);
    label1.textColor = MYBlock;
    [self.view addSubview:label1];
    
    self.inputView = [[SMSCodeInputView alloc] initWithFrame:CGRectMake(20, label1.bottom + 40, MY_Screen_W - 40, 60)];
    self.inputView.backgroundColor = UIColor.whiteColor;
    self.inputView.codeCount = 6;
    __weak typeof(self) weakSelf = self;
    self.inputView.SMSCodeInputViewBlock = ^(NSString * _Nonnull code) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        DLog(@"eeee===%@",code);
        if (strongSelf.type == 4) {
            [[HttpHelper sharedInstance] sendPost:@"api/user/login" parameters:
             @{
                @"phone":strongSelf.phone,
                @"code":code,
                @"areaCode":strongSelf.areaCode
            } success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
                DLog(@"sucess===%@",responseObject.data[@"data"]);
                if (responseObject.code == 1) {
                    [UserInfoManager sharedManager].iToken = responseObject.data[@"data"][@"token"];
                    [[HttpHelper sharedInstance] sendGet:@"api/user" parameters:@{} success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject1) {
                        if (responseObject1.code == 1) {
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [[UserInfoManager sharedManager] analyzeUserIToken:responseObject.data[@"data"][@"token"]];
                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                    TabBarController *tabbarController = [[TabBarController alloc] init];
                                    MYAPP.tarbar = tabbarController;
                                    MYAPP.window.rootViewController = tabbarController;
                                });
                            });
                        }
                    } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
                        
                    }];
                    
                }else{
                    [QMUITips showError:responseObject.message];
                }
                
            } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
                
            }];
        }else if(strongSelf.type == 1){
            [[HttpHelper sharedInstance] sendPut:@"api/user/changePhone" parameters: @{
                @"phone":strongSelf.phone,
                @"code":code,
                @"areaCode":strongSelf.areaCode
            } success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
                DLog(@"change===%@",responseObject);
                [[UserInfoManager sharedManager] initEmptyData];
                if (responseObject.code == 1) {
                    [[UserInfoManager sharedManager] getUserInfoData:^(BOOL flag) {
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [strongSelf.navigationController popToRootViewControllerAnimated:YES];
                        });
                    }];
                    

                }else{
                    [QMUITips showError:responseObject.message];
                }
            } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
                
            }];
        }else if(strongSelf.type == 3){
            [[HttpHelper sharedInstance] sendPut:@"api/user/bindPhone" parameters: @{
                @"phone":strongSelf.phone,
                @"code":code,
                @"areaCode":strongSelf.areaCode
            } success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
                DLog(@"change===%@",responseObject);
                [[UserInfoManager sharedManager] initEmptyData];
                [QMUITips showSucceed:LocalizedString(@"修改成功,请重新登录！")];
                if (responseObject.code == 1) {
                    [[UserInfoManager sharedManager] getUserInfoData:^(BOOL flag) {
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [strongSelf.navigationController popToRootViewControllerAnimated:YES];
                        });
                    }];
                    

                }else{
                    [QMUITips showError:responseObject.message];
                }
            } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
                
            }];
        }
    };
    [self.view addSubview:self.inputView];
    
    _nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, self.inputView.bottom + 30, MY_Screen_W - 40, 44)];
    [_nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [_nextBtn setTitle:@"重新获取" forState:UIControlStateNormal];
    _nextBtn.titleLabel.font = MY_SCALE_RegularFONT(13);
    _nextBtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    [_nextBtn setTitleColor:MYRed forState:UIControlStateNormal];
    [_nextBtn addTarget:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_nextBtn];
    [self getCodeSuccess];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self.inputView becomeFirstResponder];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.inputView resignFirstResponder];
    NSLog(@"获取到输入: %@", self.inputView.codeText);
}

-(void)getCode{
    if(![[_nextBtn titleForState:UIControlStateNormal] isEqualToString:LocalizedString(@"重新获取")]){
        return;
    }
    if(self.type == 3 || self.type == 1){
        [QMUITips showLoadingInView:self.view];
        [[HttpHelper sharedInstance] sendPost:@"api/sms/bind/send" parameters:@{
            @"phone":self.phone,
            @"areaCode":self.areaCode
        }success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
            DLog(@"code===%@",responseObject.data);
            [QMUITips hideAllTipsInView:self.view];
            if (responseObject.code == 1) {
                [QMUITips showSucceed:LocalizedString(@"验证码获取成功")];
                [self getCodeSuccess];
            }else{
//                if(responseObject.data[@"data"][@"errorCode"]){
//
//                }
                [QMUITips showError:LocalizedString(@"验证码获取频繁，请稍后再试")];
            }
            
        } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
            [QMUITips hideAllTipsInView:self.view];
        }];
    }else{
        NSDictionary *dic =@{
            @"phone":self.phone,
            @"areaCode":self.areaCode
        };
        [QMUITips showLoadingInView:self.view];
        [[HttpHelper sharedInstance] sendPost:@"api/sms/login/send" parameters:dic success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
            DLog(@"code===%@",responseObject.data);
            [QMUITips hideAllTipsInView:self.view];
            if (responseObject.code == 1) {
                [self getCodeSuccess];
            }else{
                [QMUITips showError:responseObject.message];
            }
            
        } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
            [QMUITips hideAllTipsInView:self.view];
        }];
    }
}

// 验证码获取成功
- (void)getCodeSuccess {
    [_nextBtn setTitleColor:MYBlock forState:UIControlStateNormal];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.num = 60;
        if (self.mtTimer) {
            self.mtTimer = nil;
        }
        self.mtTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerClick:) userInfo:nil repeats:YES];
    });
}


-(void)timerClick:(NSTimer *)timer{
    NSString *text = [NSString stringWithFormat:@"%zds %@",_num,LocalizedString(@"后重新获取验证码")];
    [_nextBtn setTitle:text forState:UIControlStateNormal];
    _num --;
    if (_num == 0) {
        _num = 60;
        [timer invalidate];
        [_nextBtn setTitle:LocalizedString(@"重新获取") forState:UIControlStateNormal];
        [_nextBtn setTitleColor:MYBlue forState:UIControlStateNormal];
    }
}

@end
